package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

class ConstructBinaryTreeFromPreorderAndInorderTraversal {
    // 2023-04-27 10:51:42
    public static void main(String[] args) {
        Solution solution = new ConstructBinaryTreeFromPreorderAndInorderTraversal().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        private Map<Integer, Integer> indexMap;

        public TreeNode buildTree(int[] preorder, int[] inorder) {
            int n = preorder.length; // 构造哈希映射，帮助我们快速定位根节点
            indexMap = new HashMap<Integer, Integer>();
            for (int i = 0; i < n; i++) {
                indexMap.put(inorder[i], i);
            }
            // 每次递归的应该是传入前序遍历和中序遍历的起始坐标
            return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
        }

        private TreeNode myBuildTree(int[] preorder, int[] inorder,
                                     int preorder_left, int preorder_right,
                                     int inorder_left, int inorder_right) {
            if (preorder_left > preorder_right) {
                return null;
            }

            // 找到根节点，即前序遍历的第一个节点
            int preorder_root = preorder_left;
            // 先把根节点建立出来
            TreeNode root = new TreeNode(preorder[preorder_root]);

            // 找到根节点在中序遍历中的位置
            Integer root_index = indexMap.get(preorder[preorder_root]);
            int length = root_index - inorder_left;
            root.left = myBuildTree(preorder, inorder,
                    preorder_root + 1, preorder_root + length,
                    inorder_left, root_index - 1);
            root.right = myBuildTree(preorder, inorder,
                    preorder_left + length + 1, preorder_right,
                    root_index + 1, inorder_right);
            return root;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}